package edu.hitwh.filter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import org.springframework.stereotype.Component;

import edu.hitwh.client.AuthApi;
import edu.hitwh.record.BorrowerRecord;
import edu.hitwh.record.LibrarianRecord;
import edu.hitwh.wrapper.Resp;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

@Component
@RequiredArgsConstructor
public class AuthFilter implements Filter {
    private final AuthApi authApi;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        String path = request.getRequestURI();

        if (!path.startsWith("/transaction")) {
            chain.doFilter(request, response);
            return;
        }

        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Basic ")) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or invalid Authorization header");
            return;
        }

        String base64Credentials = authHeader.substring("Basic ".length()).trim();
        String credentials;

        try {
            credentials = new String(Base64.getDecoder().decode(base64Credentials), StandardCharsets.UTF_8);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Base64 encoding");
            return;
        }

        String[] parts = credentials.split(":", 2);
        if (parts.length != 2) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid credentials format");
            return;
        }

        String email = parts[0];
        String password = parts[1];

        var authResp = new Resp<Boolean>();
        if(path.startsWith("/transactions/search")) {
            authResp = authApi.authenticateLibrarian(
                LibrarianRecord.builder()
                .email(email)
                .password(password)
                .build()
            );
        } else {
            authResp = authApi.authenticateBorrower(
                BorrowerRecord.builder()
                .email(email)
                .password(password)
                .build()
            );
        }

        if(!authResp.getSuccess()) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Request failed. Authentication Server responded " + authResp.getMessage());
            return;
        }
        // 调用远程认证服务
        boolean authorized = authResp.getData();  // 假设这个方法返回 boolean
        if (!authorized) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed");
            return;
        }

        // 通过认证，放行请求
        chain.doFilter(request, response);
    }
}